<?php
/**
 * 添加工地日志图片
 * User: Administrator
 * Date: 2018\8\10 0010
 * Time: 13:25
 */

namespace app\lib\Order\OrderConstructionLog;


use app\model\OrderConstructionImgModel;

class AddOrderConstructionImg
{
    protected $replyId;
    protected $imgId;
    protected $opUid;
    public function __construct($replyId,$imgId,$opUid)
    {
        $this->replyId = $replyId;
        $this->imgId   = $imgId;
        $this->opUid   = $opUid;
    }

    /**
     * 验证
     * @return bool
     * @throws \Exception
     */
    protected function check(){
        if(empty($this->replyId) || !is_numeric($this->replyId)){
            exception('未获取到工地日志id');
        }

        if(empty( $this->imgId) || !is_numeric($this->replyId)){
            exception('未获取到图片id');
        }
        return true;
    }

    /**
     * 执行代码
     * @return bool
     * @throws \Exception
     */
    public function save(){
        /*参数验证*/
        $this->check();
        $model = new OrderConstructionImgModel();
        /*验证是否存在图片*/
        $map =  [$model->_constructionLogId=>$this->replyId];
        $id  =  $model->where($map)->value($model->_id);
        /*如果存在就全部删除*/
        if($id){
            if(!($model->where($map)->delete())){
                exception('删除工地图片失败');
            }
        }
        /*新增图片*/
        $data =  [
          $model->_constructionLogId=>$this->replyId,
          $model->_imgId=>$this->imgId,
          $model->_createId =>$this->opUid,
          $model->_createTime =>time(),
        ];
        $result =  $model->insert($data);
        if(!$result){
            exception('上传工地图片失败');
        }
        return true;
    }

}